<template>
  <el-dialog v-model="dialogVisible" title="曲谱上传" width="500px" append-to-body>
    <el-form :model="form" label-width="80px">
      <el-form-item label="歌曲名称">
        <span>{{ songName }}</span>
      </el-form-item>
      <el-form-item label="曲谱文件" prop="file">
        <el-upload
          class="upload-demo"
          :action="false"
          :auto-upload="false"
          :limit="1"
          accept=".txt,.pdf,.doc,.docx"
          :on-change="handleFileChange"
          :on-exceed="handleExceed"
        >
          <el-button type="primary">选择文件</el-button>
          <template #tip>
            <div class="el-upload__tip">
              支持 .txt/.doc/.docx 格式文件
            </div>
          </template>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitUpload" :loading="uploading">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref } from 'vue';
import { uploadSheet } from '@/api/system/sing';
import { ElMessage } from "element-plus";
const props = defineProps({
  songName: {
    type: String,
    default: ''
  },
  singId: {
    type: [String, Number],
    default: ''
  }
});

const emit = defineEmits(['success']);

const dialogVisible = ref(false);
const uploading = ref(false);
const form = ref({
  file: null
});

const handleFileChange = (file) => {
  form.value.file = file.raw;
};

const handleExceed = () => {
  ElMessage.warning('只能上传一个文件');
};

const submitUpload = async () => {
  if (!form.value.file) {
    ElMessage.warning('请选择要上传的文件');
    return;
  }
  
  uploading.value = true;
  try {
    const formData = new FormData();
    formData.append('file', form.value.file);
    // formData.append('singId', props.singId);
    
    const res = await uploadSheet(props.singId, formData);
    if (res.code === 200) {
      ElMessage.success('上传成功');
      dialogVisible.value = false;
      emit('success');
    }
  } catch (error) {
    console.error('上传失败:', error);
    ElMessage.error('上传失败');
  } finally {
    uploading.value = false;
  }
};

// 对外暴露显示弹窗的方法
defineExpose({
  showDialog: () => {
    dialogVisible.value = true;
  }
});
</script>

<style scoped>
.upload-demo {
  text-align: left;
}
.dialog-footer {
  padding-top: 20px;
  text-align: right;
}
</style>